package com.highcom.dao.impl;

import com.highcom.dao.AccountMapper;
import com.highcom.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountMapperImpl implements AccountMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;



    @Override
    public List<Account> findAll() {
        String sql = "select * from account";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
    }

    @Override
    public Account findById(Integer id) {
        String sql = "select * from account where id=?";
        RowMapper<Account> rm = new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setId(rs.getInt("id"));
                account.setName(rs.getString("name"));
                account.setMoney(rs.getDouble("money"));
                return account;
            }
        };
        return jdbcTemplate.queryForObject(sql,rm,id);
    }

    @Override
    public void save(Account account) {
        String sql = "insert into account (name,money) values (?,?)";
        jdbcTemplate.update(sql,account.getName(),account.getMoney());
    }

    @Override
    public void delete(Integer id) {
        String sql = "delete from account where id=?";
        jdbcTemplate.update(sql,id);
    }

    @Override
    public void update(Account account) {
        String sql = "update account set name = ?,money=? where id=?";
        jdbcTemplate.update(sql,account.getName(),account.getMoney(),account.getId());
    }

    @Override
    public Long getCount() {
        String sql = "select count(id) from account";
        return null;
    }

    @Override
    public String findNameByid(String id) {
        String sql = "select name from account where id=?";
        return jdbcTemplate.queryForObject(sql,String.class,id);
    }
}
